<template>
  <div>

    <!--    线路分配-->
    <div v-if="active==0">
      <a-descriptions title="订单分类信息:">
        <a-descriptions-item label="订单数量">
          {{ orderDetailsData.orderClassify.total }}
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">
          {{ orderDetailsData.orderClassify.createDate }}
        </a-descriptions-item>

        <br/>
        <a-descriptions-item label="起点机构">
          {{ orderDetailsData.startCoreOrg.name }}
        </a-descriptions-item>

        <a-descriptions-item label="终点机构">
          {{ orderDetailsData.endCoreOrg.name }}
        </a-descriptions-item>
      </a-descriptions>

      <p><b><strong>订单数据:</strong></b></p>
      <el-table :data="orderDetailsData.orderVOS">
        <el-table-column label="发件人" prop="senderName"/>
        <el-table-column label="发件人电话" prop="senderPhone"/>
        <el-table-column label="发件人地址" prop="senderAddress"/>
        <el-table-column label="收件人" prop="receiverName"/>
        <el-table-column label="收件人电话" prop="receiverPhone"/>
        <el-table-column label="收件人地址" prop="receiverAddress"/>
        <el-table-column label="距离(千米)" prop="distance"/>
        <el-table-column label="金额(元)" prop="amount"/>
        <el-table-column label="下单时间" prop="createTime"/>
      </el-table>


      <!--      高德地图-->
      <p><b><strong>地图:</strong></b></p>
      <el-container>
        <el-aside width="800px">
          <div id="container" style="height: 500px"></div>
          <div id="panel"></div>
        </el-aside>
        <el-main>
          <el-form ref="form" :model="taskPickUpDispatchFrom" label-width="120px">
            <el-form-item label="分配线路:">
              <el-select v-model="taskPickUpDispatchFrom.agencyId" placeholder="请选择线路" @change="showMapLine"
                         value-key="id"
              >
                <el-option label="请选择" value=""/>
                <el-option v-for="(item,index) in transportLineData" :label="item.name" :value="item" :key="item.id"/>
              </el-select>
            </el-form-item>

            <el-form-item label="快递员分配:">
              <el-select v-model="taskPickUpDispatchFrom.courierId" placeholder="请选择快递员">
                <el-option label="请选择" value=""/>
                <el-option v-for="(item,index) in courierData" :value="item.id" :label="item.name"/>
              </el-select>
            </el-form-item>

            <el-form-item label="预计完成时间:">
              <el-date-picker
                v-model="taskPickUpDispatchFrom.estimatedEndTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:SS"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item label="备注:">
              <el-input
                type="textarea"
                autosize
                placeholder="输入你想输入的备注"
                v-model="taskPickUpDispatchFrom.mark"
              >
              </el-input>
            </el-form-item>
          </el-form>
        </el-main>
      </el-container>
    </div>

    <!--    分配车次车辆-->
    <div v-if="active==1">
      <el-form ref="form" :model="truckAndTripsAndDriverFrom" label-width="120px">
        <el-form-item label="分配车次:">
          <el-select v-model="truckAndTripsAndDriverFrom.tripsId" placeholder="请选择车次" @change="findTransportTripsById">
            <el-option v-for="(item,index) in tripsData" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="分配车辆司机">
          <el-select v-model="driver" placeholder="请选择车辆司机" value-key="id">
            <el-option v-for="(item,index) in truckData"
                       :label="item.truckDto.licensePlate+'----'+item.globalUserDTO.name" :value="item" :index="index"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="active==2">
      <el-form ref="from" :model="taskTransportFrom" label-width="120px">
        <el-form-item label="计划发车时间">
          <el-date-picker
            v-model="taskTransportFrom.planDepartureTime"
            type="date"
            placeholder="选择发车时间"
            value-format="yyyy-MM-dd HH:mm:SS"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="计划到达时间">
          <el-date-picker
            v-model="taskTransportFrom.planArrivalTime"
            type="date"
            placeholder="选择到达时间"
            value-format="yyyy-MM-dd HH:mm:SS"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划提货时间">
          <el-date-picker
            v-model="taskTransportFrom.planPickUpGoodsTime"
            type="date"
            placeholder="选择提货时间"
            value-format="yyyy-MM-dd HH:mm:SS"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划交付时间">
          <el-date-picker
            v-model="taskTransportFrom.planDeliveryTime"
            type="date"
            placeholder="选择交付时间"
            value-format="yyyy-MM-dd HH:mm:SS"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="active==3">
      <el-form ref="form" :model="driverJobFrom" label-width="120px">
        <el-form-item label="计划发车时间">
          <el-date-picker
            v-model="driverJobFrom.planDepartureTime"
            type="date"
            placeholder="选择发车时间"
            value-format="yyyy-MM-dd HH:mm:SS"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="计划到达时间">
          <el-date-picker
            v-model="driverJobFrom.planArrivalTime"
            type="date"
            placeholder="选择发车时间"
            value-format="yyyy-MM-dd HH:mm:SS"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </div>


    <el-steps :active="active" finish-status="success">
      <el-step title="分配线路"></el-step>
      <el-step title="分配车次车辆司机"></el-step>
      <el-step title="创建运输任务"></el-step>
      <el-step title="创建司机运输作业"></el-step>
    </el-steps>

    <el-button v-if="active>0" style="margin-top: 12px;" @click="previous">上一步</el-button>
    <el-button style="margin-top: 12px;" @click="next">下一步</el-button>
  </div>
</template>

<script>
import index from '@/api/work/transportOrder'

export default {
  name: 'transportAllocation',
  data() {
    return {
      //司机作业表单
      driverJobFrom: {
        startAgencyId: '',//起始机构
        endAgencyId: '',//终点机构
        driverId: '',//司机id
        taskTransportId: '',//运输任务Id
        planDepartureTime: '',//计划发车时间
        planArrivalTime: ''//计划到达时间
      },
      //运输任务数据
      taskTransportFrom: {
        transportTripsId: '',//车次Id
        startAgencyId: '',//起始机构Id
        endAgencyId: '',//终点机构Id
        truckId: '',//车辆Id
        planDepartureTime: '',//计划发车时间
        planArrivalTime: '',//计划到达时间
        planPickUpGoodsTime: '',//计划提货时间
        planDeliveryTime: '',//计划交付时间
        transportOrderIds: []//运单Id集合
      },
      //下拉框选择的数据
      driver: {},
      //车次车辆数据
      truckAndTripsAndDriverFrom: {
        tripsId: '',//车次ID
        truckId: '',//车辆Id
        driverId: '',//司机Id
        orderClassifyId: '',//订单分类id
        cacheLineId: ''//线路Id
      },
      taskPickUpDispatchFrom: {
        lineId: '',
        orderId: '',
        taskType: 1,
        agencyId: '',
        courierId: '',
        status: 2,
        estimatedEndTime: '',
        assignedStatus: 2,
        mark: ''
      },
      a: '',
      active: 0,
      transportLineData: [],
      //订单详情数据
      orderDetailsData: {},
      orderId: '',
      //高德地图,
      map: null,
      driving: null,
      //订单分类中的起点机构
      orderClassifyStartMarker: null,
      //订单分类中的终点机构
      orderClassifyEndMarker: null,
      //图片
      endIcon: null,
      startIcon: null,
      //快递员数据
      courierData: [],
      tripsData: [],
      truckData: []//车次,车辆,司机数据
    }
  },

  methods: {
    /**
     * 新增司机作业单
     */
    addDriverJob() {
      this.driverJobFrom.startAgencyId = this.orderDetailsData.startCoreOrg.id
      this.driverJobFrom.endAgencyId = this.orderDetailsData.endCoreOrg.id
      this.driverJobFrom.driverId = this.driver.globalUserDTO.id
      index.addDriverJob(this.driverJobFrom).then(data => {
        this.$message({
          showClose: true,
          message: data.message,
          type: 'success'
        })
        this.$router.push({ path: '/transport-info-index' })
      }).catch(e => {

      })
    },
    addTaskTransport() {
      /**
       * 进行赋值
       */
      this.taskTransportFrom.transportTripsId = this.driver.id
      this.taskTransportFrom.truckId = this.driver.truckDto.id
      this.taskTransportFrom.startAgencyId = this.orderDetailsData.startCoreOrg.id
      this.taskTransportFrom.endAgencyId = this.orderDetailsData.endCoreOrg.id
      let order = this.orderDetailsData.orderVOS
      for (let i = 0; i < order.length; i++) {
        this.taskTransportFrom.transportOrderIds.push(order[i].transportOrderId)
      }
      index.addTaskTransport(this.taskTransportFrom).then(data => {
        this.driverJobFrom.taskTransportId = data.data.id
        this.$message({
          showClose: true,
          message: data.message,
          type: 'success'
        }).call(e => {

        })
      })
    },
    /**
     * 添加订单分离车辆司机车次关联表以及订单分类和线路的中间表
     */
    orderClassifyTripsTruckDriverAdd() {
      /**
       * 赋值
       */
      this.truckAndTripsAndDriverFrom.cacheLineId = this.driver.transportLineId
      this.truckAndTripsAndDriverFrom.tripsId = this.driver.id
      this.truckAndTripsAndDriverFrom.truckId = this.driver.truckDto.id
      this.truckAndTripsAndDriverFrom.orderClassifyId = this.orderDetailsData.orderClassify.id
      this.truckAndTripsAndDriverFrom.driverId = this.driver.globalUserDTO.id

      index.orderClassifyTripsTruckDriverAdd(this.truckAndTripsAndDriverFrom).then(data => {
        this.$message({
          showClose: true,
          message: data.message,
          type: data.flag == true ? 'success' : 'error'
        })
      }).catch(e => {
      })
    },

    /**
     *根据车次id查询出车辆,司机信息
     * */
    findTransportTripsById() {
      index.findTransportTripsById(this.truckAndTripsAndDriverFrom.tripsId).then(data => {
        this.truckData = data.data
      }).catch(e => {
      })
    },
    /**
     *根据线路获取对应的车次数据
     */
    findTripsAllByLineId(id) {
      index.findTripsAllByLineId(id).then(data => {
        this.tripsData = data.data
      }).catch(e => {
      })
    },
    /**
     * 批量添加取件任务
     */
    addTaskPickupDispatch() {
      let taskPickUpDispatchData = []
      this.taskPickUpDispatchFrom.agencyId = this.taskPickUpDispatchFrom.agencyId.startAgency.id
      for (let i = 0; i < this.orderDetailsData.orderVOS.length; i++) {
        this.taskPickUpDispatchFrom.orderId = this.orderDetailsData.orderVOS[i].id
        taskPickUpDispatchData.push(this.taskPickUpDispatchFrom)
      }
      index.addTaskPickupDispatch(taskPickUpDispatchData).then(data => {
        this.$message({
          showClose: true,
          type: 'success',
          message: data.data
        })
      }).catch(e => {
        this.active = 0
      })
    },
    findCourier(agencyId) {
      index.findCourier(agencyId).then(data => {
        this.courierData = []
        this.courierData = data.data
      }).catch(e => {
      })
    },
    showMapLine(item) {
      this.lineId = item.id
      this.taskPickUpDispatchFrom.courierId = ''
      console.log('', item)
      if (this.map) {
        this.map = null
        this.initMap()
        this.findCourier(item.startAgency.id)
      } else {
        this.$message({
          type: 'warning',
          showClose: true,
          message: '请等待地图显示出来!'
        })
        return
      }
      this.driving = new AMap.Driving({
        map: this.map
      })
//        panel: "panel"
      // 根据起终点经纬度规划驾车导航路线
      setTimeout(() => {
        this.driving.search(new AMap.LngLat(item.startAgency.longitude, item.startAgency.latitude), new AMap.LngLat(item.endAgency.longitude, item.endAgency.latitude), (status, result) => {
          // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
          if (status === 'complete') {
            log.success('绘制驾车路线完成')
          } else {
            log.error('获取驾车数据失败：' + result)
          }
        })
      }, 1000)
    },
    previous() {
      if (--this.active <= 0) {
        this.active = 0
      }
    },
    initMap() {
      this.map = new AMap.Map('container', {
        zoom: 13,
        center: [this.orderDetailsData.startCoreOrg.longitude, this.orderDetailsData.startCoreOrg.latitude],
        resizeEnable: true
      })
      //绘制起始标记点
      this.startIcon = new AMap.Icon({
        // 图标尺寸
        size: new AMap.Size(25, 34),
        // 图标的取图地址
        image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
        // 图标所用图片大小
        imageSize: new AMap.Size(135, 40),
        // 图标取图偏移量
        imageOffset: new AMap.Pixel(-9, -3)
      })

      //绘制终点标记点
      this.endIcon = new AMap.Icon({
        size: new AMap.Size(25, 34),
        image: '//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png',
        imageSize: new AMap.Size(135, 40),
        imageOffset: new AMap.Pixel(-95, -3)
      })

      this.orderClassifyStartMarker = new AMap.Marker({
        position: new AMap.LngLat(this.orderDetailsData.startCoreOrg.longitude, this.orderDetailsData.startCoreOrg.latitude),
        icon: this.startIcon,
        offset: new AMap.Pixel(-13, -30)
      })

      this.orderClassifyEndMarker = new AMap.Marker({
        position: new AMap.LngLat(this.orderDetailsData.endCoreOrg.longitude, this.orderDetailsData.endCoreOrg.latitude),
        icon: this.endIcon,
        offset: new AMap.Pixel(-13, -30)
      })
      this.map.add(this.orderClassifyStartMarker)
      this.map.add(this.orderClassifyEndMarker)
      log.success('地图绘制成功!')
    },
    next() {
      ++this.active
      if (this.active === 1) {
        this.addTaskPickupDispatch()
        this.findTripsAllByLineId(this.lineId)
      }
      if (this.active === 2) {
        this.orderClassifyTripsTruckDriverAdd()
      }
      if (this.active === 3) {
        this.addTaskTransport()
      }
      if (this.active === 4) {
        this.addDriverJob()
      }
    },
    findTransportOrderDetailsByOrderById(orderId) {
      index.findTransportOrderDetailsByOrderById(orderId).then(data => {
        this.orderDetailsData = data.data
        setTimeout(this.initMap, 3000)

      }).catch(e => {
      })
    },
    queryAll() {
      index.queryAllTransportLine().then(data => {
        this.transportLineData = data.data
      }).catch(e => {
      })
    }
  },
  mounted() {
    if (this.$route.params && this.$route.params.id) {
      this.orderId = this.$route.params.id
      this.findTransportOrderDetailsByOrderById(this.orderId)
      this.queryAll()
    }
  }
}
</script>

<style scoped>

</style>
